#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
GUI组件模块 - 根据简化版ui_design.html优化
采用左右分栏布局：左侧功能面板，右侧标签页内容
"""

import tkinter as tk
from tkinter import ttk, scrolledtext
from typing import Optional, Dict, Callable, Any
CORE_STEPS = ("organize", "start_creat_list", "generate_nfo")


class FolderSelector:
    """
    文件夹选择组件 - 顶部横向布局
    
    提供文件夹选择功能，包括输入框、浏览按钮和回调机制。
    
    Args:
        parent: 父容器组件
        callback: 文件夹选择后的回调函数
    """
    
    def __init__(self, parent: tk.Widget, callback: Optional[Callable[[str], None]] = None):
        """
        初始化文件夹选择器
        
        Args:
            parent: 父容器组件
            callback: 文件夹选择后的回调函数
        """
        self.parent = parent
        self.callback = callback
        self.folder_var = tk.StringVar()
        self.create_widgets()
    
    def create_widgets(self) -> None:
        """创建文件夹选择器组件"""
        # 文件夹选择框架
        folder_frame = ttk.Frame(self.parent)
        folder_frame.pack(fill='x', pady=(0, 10))
        
        # 标签
        ttk.Label(folder_frame, text="电影文件夹:").pack(side='left')
        
        # 输入框（只读）
        folder_entry = ttk.Entry(folder_frame, textvariable=self.folder_var, width=50, state='readonly')
        folder_entry.pack(side='left', fill='x', expand=True, padx=(5, 5))
        
        # 浏览按钮
        browse_button = ttk.Button(folder_frame, text="浏览", command=self.browse_folder)
        browse_button.pack(side='right')
    
    def browse_folder(self) -> None:
        """浏览文件夹"""
        try:
            from .gui_manager import DialogManager
            folder = DialogManager.select_folder("选择电影文件夹")
            if folder:
                self.folder_var.set(folder)
                if self.callback:
                    self.callback(folder)
        except ImportError as e:
            print(f"导入DialogManager失败: {e}")
        except Exception as e:
            print(f"选择文件夹时出错: {e}")
    
    def get_folder(self) -> str:
        """获取当前选择的文件夹路径"""
        return self.folder_var.get()
    
    def set_folder(self, folder: str) -> None:
        """设置文件夹路径"""
        self.folder_var.set(folder)


class LeftFunctionPanel:
    """
    左侧功能面板
    
    包含核心流程和辅助工具的功能按钮、选项和进度显示。
    """
    
    # 布局常量
    PANEL_WIDTH = 320
    PADDING = 10
    BUTTON_SPACING = 15
    PROGRESS_FONT_SIZE = 9
    
    def __init__(self, parent: tk.Widget, callbacks: Optional[Dict[str, Callable]] = None, grouped_controls: Optional['GroupedControls'] = None):
        """
        初始化左侧功能面板
        
        Args:
            parent: 父容器组件
            callbacks: 回调函数字典
            grouped_controls: 分组控制组件实例
        """
        self.parent = parent
        self.callbacks = callbacks or {}
        self.buttons = {}
        self.checkboxes = {}
        self.progress_bars = {}
        self.progress_labels = {}
        self.grouped_controls = grouped_controls
        
        # 选项变量
        self.delete_list_var = tk.BooleanVar(value=False)
        self.allow_overwrite_var = tk.BooleanVar(value=False)
        self.download_images_var = tk.BooleanVar(value=True)
        
        self.create_widgets()
    
    def create_widgets(self) -> None:
        """创建左侧功能面板"""
        main_container = self._create_main_container()
        left_frame, self.right_frame = self._create_layout_frames(main_container)
        
        self._create_core_process(left_frame)
        self._create_helper_tools(left_frame)
    
    def _create_main_container(self) -> ttk.Frame:
        """创建主布局容器"""
        main_container = ttk.Frame(self.parent)
        main_container.pack(fill='both', expand=True, padx=self.PADDING, pady=self.PADDING)
        return main_container
    
    def _create_layout_frames(self, parent: ttk.Frame) -> tuple[ttk.Frame, ttk.Frame]:
        """创建左右分栏框架"""
        # 左侧框架
        left_frame = ttk.Frame(parent, width=self.PANEL_WIDTH)
        left_frame.pack(side='left', fill='y', padx=(0, self.PADDING))
        left_frame.pack_propagate(False)
        
        # 右侧内容区域
        right_frame = ttk.Frame(parent)
        right_frame.pack(side='right', fill='both', expand=True)
        
        return left_frame, right_frame
    
    def _create_core_process(self, parent: ttk.Frame) -> None:
        """创建核心流程区域"""
        core_frame = ttk.LabelFrame(parent, text="核心流程", padding=str(self.PADDING))
        core_frame.pack(fill='x', pady=(0, self.PADDING))
        
        # 步骤1：整理电影文件
        self._create_step_group(
            core_frame, "① 整理电影文件", 
            "将每个视频放入独立的同名文件夹",
            "organize", "organize_movies", add_progress=False
        )
        
        # 步骤2：爬取TMDb链接
        step2_frame = self._create_step_group(
            core_frame, "② 爬取TMDb链接", 
            "", "start_creat_list", 
            "start_creating_list_processing", add_progress=False
        )
        self._create_step2_options(step2_frame)
        
        # 步骤3：爬取电影信息与海报
        step3_frame = self._create_step_group(
            core_frame, "③ 爬取电影信息与海报", 
            "", "generate_nfo", 
            "generate_nfo_files", add_progress=False
        )
        self._create_step3_options(step3_frame)
        
        # 统一的核心流程进度条
        self._create_unified_progress(core_frame)
    
    def _create_step2_options(self, parent: ttk.Frame) -> None:
        """创建步骤2的选项"""
        self.checkboxes["delete_list"] = ttk.Checkbutton(
            parent,
            text="重新扫描所有电影（忽略已有）",
            variable=self.delete_list_var
        )
        self.checkboxes["delete_list"].pack(anchor='w', padx=5, pady=(5, 0))
    
    def _create_step3_options(self, parent: ttk.Frame) -> None:
        """创建步骤3的选项"""
        options_frame = ttk.Frame(parent)
        options_frame.pack(fill='x', padx=5, pady=(5, 0))
        
        self.checkboxes["allow_overwrite"] = ttk.Checkbutton(
            options_frame,
            text="覆盖已存在的NFO文件",
            variable=self.allow_overwrite_var
        )
        self.checkboxes["allow_overwrite"].pack(anchor='w')
        
        self.checkboxes["download_images"] = ttk.Checkbutton(
            options_frame,
            text="下载海报与同人画",
            variable=self.download_images_var
        )
        self.checkboxes["download_images"].pack(anchor='w')
    
    def _create_unified_progress(self, parent: ttk.Frame) -> None:
        """创建统一的核心流程进度条"""
        progress_frame = ttk.Frame(parent)
        progress_frame.pack(fill='x', pady=(self.PADDING, 0))
        
        # 统一进度条
        self.progress_bars["core_process"] = ttk.Progressbar(progress_frame, mode='determinate')
        self.progress_bars["core_process"].pack(fill='x', pady=(0, 2))
        
        # 统一进度标签
        self.progress_labels["core_process"] = ttk.Label(
            progress_frame, text="", 
            font=('', self.PROGRESS_FONT_SIZE), foreground='blue'
        )
        self.progress_labels["core_process"].pack(anchor='w')
        
        # 兼容性映射
        self._map_core_progress_references()
    
    def _map_core_progress_references(self) -> None:
        """映射核心流程步骤的进度条引用到统一进度条"""
        core_steps = ["organize", "start_creat_list", "generate_nfo"]
        for step in core_steps:
            self.progress_bars[step] = self.progress_bars["core_process"]
            self.progress_labels[step] = self.progress_labels["core_process"]
    
    def _create_helper_tools(self, parent: ttk.Frame) -> None:
        """创建辅助工具区域"""
        helper_frame = ttk.LabelFrame(parent, text="辅助工具", padding=str(self.PADDING))
        helper_frame.pack(fill='x')
        
        self._create_step_group(
            helper_frame, "仅下载海与同人画（根据NFO）", 
            "根据文件夹内的视频同名NFO文件补充下载海报",
            "download_from_nfo", "download_posters_from_nfo"
        )
    
    def _create_step_group(self, parent: ttk.Frame, title: str, description: str, 
                          button_key: str, callback_key: str, add_progress: bool = True) -> ttk.Frame:
        """
        创建步骤组
        
        Args:
            parent: 父容器
            title: 步骤标题
            description: 步骤描述
            button_key: 按钮键名
            callback_key: 回调函数键名
            add_progress: 是否立即添加进度条
            
        Returns:
            步骤框架
        """
        step_frame = ttk.Frame(parent)
        step_frame.pack(fill='x', pady=(0, self.BUTTON_SPACING))
        
        # 移除style参数，使用默认按钮样式
        callback = self.callbacks.get(callback_key)
        self.buttons[button_key] = ttk.Button(step_frame, text=title, command=callback)
        self.buttons[button_key].pack(fill='x')
        
        # 描述文字
        if description:
            desc_label = ttk.Label(step_frame, text=description, foreground='gray')
            desc_label.pack(anchor='w', pady=(2, 5))
        
        # 如果需要立即添加进度条
        if add_progress:
            self._add_progress_to_step(step_frame, button_key)
        
        return step_frame
    
    def _add_progress_to_step(self, step_frame: ttk.Frame, button_key: str) -> None:
        """为步骤添加进度条和标签"""
        self.progress_bars[button_key] = ttk.Progressbar(step_frame, mode='determinate')
        self.progress_bars[button_key].pack(fill='x', pady=(5, 2))
        
        self.progress_labels[button_key] = ttk.Label(
            step_frame, text="", 
            font=('', self.PROGRESS_FONT_SIZE), foreground='blue'
        )
        self.progress_labels[button_key].pack(anchor='w')
    
    def get_right_frame(self) -> ttk.Frame:
        """获取右侧框架"""
        return self.right_frame
    
    def get_button(self, key: str) -> Optional[ttk.Button]:
        """获取指定按钮"""
        return self.buttons.get(key)
    
    def get_all_buttons(self) -> Dict[str, ttk.Button]:
        """获取所有按钮"""
        return self.buttons
    
    def get_options(self) -> Dict[str, bool]:
        """获取所有选项值"""
        return {
            'delete_list': self.delete_list_var.get(),
            'allow_overwrite': self.allow_overwrite_var.get(),
            'download_images': self.download_images_var.get()
        }
    
    def _get_progress_key(self, name: str) -> str:
        """获取进度条键名"""
        return "core_process" if name in CORE_STEPS else name
    
    def start_progress(self, name: str, message: str) -> None:
        """开始进度显示"""
        progress_key = self._get_progress_key(name)
        # 自动切换到处理日志标签页（仅核心流程步骤）
        if name in CORE_STEPS:
            if self.grouped_controls:
                try:
                    right_panel = self.grouped_controls.get_right_panel()
                    if right_panel and right_panel.notebook:
                        right_panel.notebook.select(1)
                except Exception as e:
                    print(f"切换日志tab失败: {e}")
        if progress_key in self.progress_bars:
            self.progress_bars[progress_key].configure(mode='indeterminate')
            self.progress_bars[progress_key].start()
        if progress_key in self.progress_labels:
            self.progress_labels[progress_key].configure(text=message)
    
    def set_progress(self, name: str, progress: int, message: str) -> None:
        """设置进度（含调试输出）"""
        progress_key = self._get_progress_key(name)
       
        if progress_key in self.progress_bars:
            self.progress_bars[progress_key].stop()
            self.progress_bars[progress_key].configure(mode='determinate')
            self.progress_bars[progress_key]['value'] = progress
          
        if progress_key in self.progress_labels:
            self.progress_labels[progress_key].configure(text=message)
    
    def complete_progress(self, name: str, message: str) -> None:
        """完成进度"""
        progress_key = self._get_progress_key(name)
        
        if progress_key in self.progress_bars:
            self.progress_bars[progress_key].stop()
            self.progress_bars[progress_key]['value'] = 100
        if progress_key in self.progress_labels:
            self.progress_labels[progress_key].configure(text=message)
    
    def stop_progress(self, name: str, message: str) -> None:
        """停止进度"""
        progress_key = self._get_progress_key(name)
        
        if progress_key in self.progress_bars:
            self.progress_bars[progress_key].stop()
            self.progress_bars[progress_key]['value'] = 0
        if progress_key in self.progress_labels:
            self.progress_labels[progress_key].configure(text=message)


class RightContentPanel:
    """
    右侧内容面板 - 标签页设计
    
    包含电影列表和处理日志两个标签页。
    """
    
    def __init__(self, parent: tk.Widget, callbacks: Optional[Dict[str, Callable]] = None):
        """
        初始化右侧内容面板
        
        Args:
            parent: 父容器组件
            callbacks: 回调函数字典
        """
        self.parent = parent
        self.callbacks = callbacks or {}
        self.notebook: Optional[ttk.Notebook] = None
        self.movie_table: Optional['MovieListTable'] = None
        self.log_display: Optional['LogDisplay'] = None
        self.create_widgets()
    
    def create_widgets(self) -> None:
        """创建右侧内容面板"""
        # 标签页控件
        self.notebook = ttk.Notebook(self.parent)
        self.notebook.pack(fill='both', expand=True)
        
        # 电影列表标签页
        movie_frame = ttk.Frame(self.notebook)
        self.notebook.add(movie_frame, text="电影列表")
        
        # 处理日志标签页
        log_frame = ttk.Frame(self.notebook)
        self.notebook.add(log_frame, text="处理日志")
        
        # 创建电影列表表格
        self.movie_table = MovieListTable(movie_frame, self.callbacks)
        
        # 创建日志显示
        self.log_display = LogDisplay(log_frame)
    
    def get_movie_table(self) -> 'MovieListTable':
        """获取电影表格"""
        return self.movie_table
    
    def get_log_display(self) -> 'LogDisplay':
        """获取日志显示"""
        return self.log_display


# 兼容性包装器 - 保持原有接口
class GroupedControls:
    """
    分组控制组件 - 兼容性包装器
    
    为了保持向后兼容性而提供的包装器类。
    """

    def __init__(self, parent: tk.Widget, callbacks: Optional[Dict[str, Callable]] = None):
        """
        初始化分组控制组件
        
        Args:
            parent: 父容器组件
            callbacks: 回调函数字典
        """
        self.parent = parent
        self.callbacks = callbacks or {}
        
        # 创建左侧功能面板
        self.left_panel = LeftFunctionPanel(parent, callbacks, grouped_controls=self)
        
        # 创建右侧内容面板
        self.right_panel = RightContentPanel(self.left_panel.get_right_frame(), callbacks)
        
        # 兼容性属性映射
        self._map_compatibility_attributes()
    
    def _map_compatibility_attributes(self) -> None:
        """映射兼容性属性"""
        self.buttons = self.left_panel.buttons
        self.checkboxes = self.left_panel.checkboxes
        self.progress_bars = self.left_panel.progress_bars
        self.progress_labels = self.left_panel.progress_labels
        self.delete_list_var = self.left_panel.delete_list_var
        self.allow_overwrite_var = self.left_panel.allow_overwrite_var
        self.download_images_var = self.left_panel.download_images_var
    
    def get_right_panel(self) -> RightContentPanel:
        """获取右侧面板"""
        return self.right_panel
    
    def get_all_buttons(self) -> Dict[str, ttk.Button]:
        """获取所有按钮"""
        return self.left_panel.get_all_buttons()
    
    def get_options(self) -> Dict[str, bool]:
        """获取所有选项值"""
        return self.left_panel.get_options()
    
    def start_progress(self, name: str, message: str) -> None:
        """开始进度显示"""
        self.left_panel.start_progress(name, message)
    
    def set_progress(self, name: str, progress: int, message: str) -> None:
        """设置进度"""
        self.left_panel.set_progress(name, progress, message)
    
    def complete_progress(self, name: str, message: str) -> None:
        """完成进度"""
        self.left_panel.complete_progress(name, message)
    
    def stop_progress(self, name: str, message: str) -> None:
        """停止进度"""
        self.left_panel.stop_progress(name, message)


class MovieListTable:
    """
    电影列表表格组件
    
    提供电影信息的表格显示、编辑和管理功能。
    """
    
    # 表格配置常量
    COLUMN_CONFIG = {
        'index': {'width': 40, 'anchor': 'center'},
        'name': {'width': 180, 'anchor': 'w'},
        'url': {'width': 350, 'anchor': 'w'}
    }
    
    COLUMN_HEADERS = {
        'index': '序号',
        'name': '电影名称', 
        'url': 'TMDb链接'
    }
    
    PADDING = 10
    
    def __init__(self, parent: tk.Widget, callbacks: Optional[Dict[str, Callable]] = None):
        """
        初始化电影列表表格
        
        Args:
            parent: 父容器组件
            callbacks: 回调函数字典
        """
        self.parent = parent
        self.callbacks = callbacks or {}
        self.movie_tree: Optional[ttk.Treeview] = None
        self.context_menu: Optional[tk.Menu] = None
        self.create_widgets()
    
    def create_widgets(self) -> None:
        """创建电影列表表格"""
        table_container = self._create_table_container()
        scrollbars = self._create_scrollbars(table_container)
        self.movie_tree = self._create_treeview(table_container, scrollbars)
        self._configure_columns()
        self._bind_events()
        self._create_context_menu()
    
    def _create_table_container(self) -> ttk.Frame:
        """创建表格容器"""
        container = ttk.Frame(self.parent)
        container.pack(fill='both', expand=True, padx=self.PADDING, pady=self.PADDING)
        return container
    
    def _create_scrollbars(self, container: ttk.Frame) -> Dict[str, ttk.Scrollbar]:
        """创建滚动条"""
        scrollbar_y = ttk.Scrollbar(container, orient='vertical')
        scrollbar_y.pack(side='right', fill='y')
        
        scrollbar_x = ttk.Scrollbar(container, orient='horizontal')
        scrollbar_x.pack(side='bottom', fill='x')
        
        return {'y': scrollbar_y, 'x': scrollbar_x}
    
    def _create_treeview(self, container: ttk.Frame, scrollbars: Dict[str, ttk.Scrollbar]) -> ttk.Treeview:
        """创建表格视图"""
        tree = ttk.Treeview(
            container,
            columns=tuple(self.COLUMN_CONFIG.keys()),
            show='headings',
            yscrollcommand=scrollbars['y'].set,
            xscrollcommand=scrollbars['x'].set
        )
        tree.pack(side='left', fill='both', expand=True)
        
        # 配置滚动条
        scrollbars['y'].config(command=tree.yview)
        scrollbars['x'].config(command=tree.xview)
        
        return tree
    
    def _configure_columns(self) -> None:
        """配置表格列"""
        for col_id, config in self.COLUMN_CONFIG.items():
            self.movie_tree.column(col_id, width=config['width'], anchor=config['anchor'])
            self.movie_tree.heading(col_id, text=self.COLUMN_HEADERS[col_id])
        
        # 配置样式
        self.movie_tree.tag_configure('url_link', foreground='blue')
    
    def _bind_events(self) -> None:
        """绑定事件"""
        self.movie_tree.bind("<ButtonRelease-1>", self._on_click)
        self.movie_tree.bind("<Double-1>", self._on_double_click)
        self.movie_tree.bind("<Button-3>", self._on_right_click)
    
    def _create_context_menu(self) -> None:
        """创建右键菜单"""
        self.context_menu = tk.Menu(self.parent, tearoff=0)
        self.context_menu.add_command(label="编辑", command=self._edit_selected)
        self.context_menu.add_command(label="删除", command=self._delete_selected)
        self.context_menu.add_separator()
        self.context_menu.add_command(label="添加新条目", command=self._add_new)
    
    def _on_click(self, event: tk.Event) -> None:
        """处理单击事件"""
        callback = self.callbacks.get('on_click')
        if callback:
            callback(event)
    
    def _on_double_click(self, event: tk.Event) -> None:
        """处理双击事件"""
        callback = self.callbacks.get('on_double_click')
        if callback:
            callback(event)
    
    def _on_right_click(self, event: tk.Event) -> None:
        """处理右键点击事件"""
        callback = self.callbacks.get('on_right_click')
        if callback:
            callback(event)
    
    def _edit_selected(self) -> None:
        """编辑选中项"""
        callback = self.callbacks.get('edit_selected')
        if callback:
            callback()
    
    def _delete_selected(self) -> None:
        """删除选中项"""
        callback = self.callbacks.get('delete_selected')
        if callback:
            callback()
    
    def _add_new(self) -> None:
        """添加新项"""
        callback = self.callbacks.get('add_new')
        if callback:
            callback()
    
    def clear(self) -> None:
        """清空表格"""
        if self.movie_tree:
            for item in self.movie_tree.get_children():
                self.movie_tree.delete(item)
    
    def add_item(self, index: int, name: str, url: str) -> None:
        """添加表格项"""
        if self.movie_tree:
            self.movie_tree.insert('', 'end', values=(index, name, url), tags=('url_link',))
    
    def get_selected_item(self) -> Optional[Dict[str, Any]]:
        """获取选中的项"""
        if not self.movie_tree:
            return None
            
        selected_items = self.movie_tree.selection()
        if selected_items:
            return self.movie_tree.item(selected_items[0])
        return None


class LogDisplay:
    """
    日志显示组件
    
    提供日志信息的显示和管理功能。
    """
    
    # 显示配置常量
    FONT_FAMILY = 'Consolas'
    FONT_SIZE = 10
    BG_COLOR = 'black'
    FG_COLOR = '#00ff00'
    PADDING = 10
    
    def __init__(self, parent: tk.Widget):
        """
        初始化日志显示组件
        
        Args:
            parent: 父容器组件
        """
        self.parent = parent
        self.log_text: Optional[scrolledtext.ScrolledText] = None
        self.create_widgets()
    
    def create_widgets(self) -> None:
        """创建日志显示区域"""
        log_container = ttk.Frame(self.parent)
        log_container.pack(fill='both', expand=True, padx=self.PADDING, pady=self.PADDING)
        
        self.log_text = scrolledtext.ScrolledText(
            log_container,
            wrap='word',
            font=(self.FONT_FAMILY, self.FONT_SIZE),
            bg=self.BG_COLOR,
            fg=self.FG_COLOR
        )
        self.log_text.pack(fill='both', expand=True)
    
    def append_log(self, message: str) -> None:
        """添加日志消息"""
        if self.log_text:
            self.log_text.insert('end', message + '\n')
            self.log_text.see('end')
    
    def clear(self) -> None:
        """清空日志"""
        if self.log_text:
            self.log_text.delete(1.0, 'end')
    
    def get_widget(self) -> Optional[scrolledtext.ScrolledText]:
        """获取日志组件"""
        return self.log_text


class StatusBar:
    """
    状态栏组件
    
    显示状态信息和提供快捷操作按钮。
    """
    
    PADDING = 10
    BUTTON_SPACING = 5
    
    def __init__(self, parent: tk.Widget, help_callback: Optional[Callable] = None,
                 list_callback: Optional[Callable] = None, lost_callback: Optional[Callable] = None,
                 reset_callback: Optional[Callable] = None):
        """
        初始化状态栏
        
        Args:
            parent: 父容器组件
            help_callback: 帮助按钮回调
            list_callback: 列表按钮回调
            lost_callback: 错误日志按钮回调
            reset_callback: 重置按钮回调
        """
        self.parent = parent
        self.help_callback = help_callback
        self.list_callback = list_callback
        self.lost_callback = lost_callback
        self.reset_callback = reset_callback
        
        self.progress_var = tk.StringVar(value="就绪")
        self.help_button: Optional[ttk.Button] = None
        self.list_button: Optional[ttk.Button] = None
        self.lost_button: Optional[ttk.Button] = None
        self.reset_button: Optional[ttk.Button] = None
        
        self.create_widgets()
    
    def create_widgets(self) -> None:
        """创建状态栏"""
        status_frame = ttk.Frame(self.parent)
        status_frame.pack(side='bottom', fill='x', padx=self.PADDING, pady=self.PADDING)
        
        # 左侧状态标签
        status_label = ttk.Label(status_frame, textvariable=self.progress_var)
        status_label.pack(side='left')
        
        # 右侧按钮区域
        self._create_buttons(status_frame)
    
    def _create_buttons(self, parent: ttk.Frame) -> None:
        """创建按钮区域"""
        button_frame = ttk.Frame(parent)
        button_frame.pack(side='right')
        
        # 使用说明按钮
        if self.help_callback:
            self.help_button = ttk.Button(
                button_frame, text="使用说明", 
                command=self.help_callback
            )
            self.help_button.pack(side='right', padx=(self.BUTTON_SPACING, 0))
        
        # 打开错误日志文件按钮
        if self.lost_callback:
            self.lost_button = ttk.Button(
                button_frame, text="打开错误日志文件", 
                command=self.lost_callback
            )
            self.lost_button.pack(side='right', padx=(self.BUTTON_SPACING, 0))
        
        # 打开电影清单文件按钮
        if self.list_callback:
            self.list_button = ttk.Button(
                button_frame, text="打开电影清单文件", 
                command=self.list_callback
            )
            self.list_button.pack(side='right', padx=(self.BUTTON_SPACING, 0))
        
        # 重置按钮
        if self.reset_callback:
            self.reset_button = ttk.Button(
                button_frame, text="重置", 
                command=self.reset_callback
            )
            self.reset_button.pack(side='right', padx=(self.BUTTON_SPACING, 0))
    
    def set_status(self, message: str) -> None:
        """设置状态信息"""
        self.progress_var.set(message)
    
    def get_status(self) -> str:
        """获取当前状态信息"""
        return self.progress_var.get()
    
    def get_progress_var(self) -> tk.StringVar:
        """获取进度变量"""
        return self.progress_var
    
    def get_reset_button(self) -> Optional[ttk.Button]:
        """获取重置按钮"""
        return self.reset_button


class MainLayout:
    """
    主界面布局管理器
    
    负责整个应用程序的主界面布局和组件管理。
    """
    
    PADDING = 10
    
    def __init__(self, root: tk.Tk, callbacks: Optional[Dict[str, Callable]] = None):
        """
        初始化主界面布局
        
        Args:
            root: 主窗口
            callbacks: 回调函数字典
        """
        self.root = root
        self.callbacks = callbacks or {}
        self.folder_selector: Optional[FolderSelector] = None
        self.grouped_controls: Optional[GroupedControls] = None
        self.status_bar: Optional[StatusBar] = None
        self.create_layout()
    
    def create_layout(self) -> None:
        """创建主界面布局"""
        # 配置主窗口的网格权重
        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=1)

        # 创建主框架
        main_frame = self._create_main_frame()
        
        # 创建各个组件
        self._create_components(main_frame)
    
    def _create_main_frame(self) -> ttk.Frame:
        """创建主框架"""
        main_frame = ttk.Frame(self.root, padding=str(self.PADDING))
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        main_frame.columnconfigure(0, weight=1)
        main_frame.rowconfigure(1, weight=1)
        return main_frame
    
    def _create_components(self, parent: ttk.Frame) -> None:
        """创建各个组件"""
        # 创建文件夹选择器
        self.folder_selector = FolderSelector(
            parent, 
            callback=self.callbacks.get('on_folder_selected')
        )

        # 创建分组控制组件
        self.grouped_controls = GroupedControls(parent, callbacks=self.callbacks)

        # 创建状态栏
        self.status_bar = StatusBar(
            parent,
            help_callback=self.callbacks.get('show_help'),
            list_callback=self.callbacks.get('open_movie_list_file'),
            lost_callback=self.callbacks.get('open_lost_file'),
            reset_callback=self.callbacks.get('reset_gui')
        )
    
    def get_folder_selector(self) -> FolderSelector:
        """获取文件夹选择器"""
        return self.folder_selector
    
    def get_grouped_controls(self) -> GroupedControls:
        """获取分组控制组件"""
        return self.grouped_controls
    
    def get_status_bar(self) -> StatusBar:
        """获取状态栏"""
        return self.status_bar

